<template>
    <van-nav-bar title="确认订单" left-text="" left-arrow @click-left="goBack" />

    <!-- 地址 -->
    <van-contact-card v-if="Object.values(Address).length > 0" type="edit" :tel="Address.mobile"
        :name="Address.consignee" @click="toAddressPage" />
    <van-contact-card v-else type="add" @click="toAddressPage" />

    <!-- 商品信息 -->
    <van-card v-for="item in productlist" :price="item.total" :title="item.product.name" class="goods-card"
        :thumb="item.product.thumbs_text" @click-thumb="toPageInfo(item.proid)" :num="item.nums">
        <template #desc>
            <div v-if="item.attrs">
                <van-tag v-for="items in item.attrs" type="warning" size="medium" style="margin-right: 10px;">{{
                    items.value }}</van-tag>
            </div>
            <div>单价： {{ item.price }}</div>
        </template>
    </van-card>

    <!--支付方式 -->
    <van-field v-model="payName" is-link readonly label="支付方式" placeholder="选择支付方式" @click="showPayPicker = true" />
    <van-popup v-model:show="showPayPicker" destroy-on-close position="bottom">
        <van-picker :columns="columnsPay" @confirm="onPayConfirm" @cancel="showPayPicker = false" />
    </van-popup>

    <!-- 优惠券单元格 -->
    <van-coupon-cell :coupons="couponlist" :chosen-coupon="chosenCoupon" @click="showList = true" />
    <!-- 优惠券列表 -->
    <van-popup v-model:show="showList" round position="bottom" style="height: 90%; padding-top: 4px;">
        <van-coupon-list :coupons="couponlist" :chosen-coupon="chosenCoupon" :disabled-coupons="disabledCoupons" @change="onCouponChange"
            :show-exchange-bar="false" />
    </van-popup>

    <!-- 订单备注 -->
    <van-field v-model="remark" rows="2" autosize label="订单备注" type="textarea" maxlength="120" placeholder="请输入订单备注"
        show-word-limit />

    <!-- 确认支付 -->
    <van-submit-bar :price="total" button-text="确认支付" @submit="onSubmit" />

</template>

<script setup>
const { proxy } = getCurrentInstance()
const goBack = () => { proxy.$router.go(-1) }
const LoginUser = reactive(proxy.$cookies.get('LoginUser') ?? {})
const Address = ref(proxy.$cookies.get('Address') ? proxy.$cookies.get('Address') : {})
const cartids = proxy.$route.query.cartids ? proxy.$route.query.cartids : 0;
const isDirectlyBuy = proxy.$route.query.isDirectlyBuy ? proxy.$route.query.isDirectlyBuy : 0;
const productlist = ref([])
const remark = ref('')

// 支付方式 
const showPayPicker = ref(false)
const payName = ref('')
const pay = ref('')
const columnsPay = [
    { text: '余额支付', value: 'money' },
    { text: '支付宝', value: 'zfb' },
    { text: '微信支付', value: 'wx' },
]

// 优惠券
const couponlist = ref([]);
const showList = ref(false);
const chosenCoupon = ref(-1);

const toAddressPage = () => {
    proxy.$router.push({
        path: '/address/index',
        query: {
            action: 'order'
        }
    })
}
onBeforeMount(() => {
    if (Object.values(Address.value).length <= 0) {
        getAddressData()
    }
    getProductData()
    getCouponData()
})
const getAddressData = async () => {
    let result = await Api.AddressOrder({
        busid: LoginUser.id,
    })

    if (result.code == 1) {
        let data = result.data
        Address.value = {
            id: data.id,
            consignee: data.consignee,
            mobile: data.mobile
        }
    }
}

const getProductData = async () => {
    let result = await Api.CartIndex({
        busid: LoginUser.id,
        cartids: cartids
    })

    if (result.code == 1) {
        productlist.value = result.data
        productlist.value.forEach((item) => {
            if (item.attrs) {
                item.attrs = JSON.parse(item.attrs)
            }
        })
    }
}

const getCouponData = async () => {
    let result = await Api.CouponOrder({
        busid: LoginUser.id
    })

    if (result.code == 1) {
        result.data.forEach((item) => {
            couponlist.value.push({
                id: item.id,
                condition: '正在活动中',
                value: 0,
                name: item.coupon.title,
                startAt: item.coupon.createtimes,
                endAt: item.coupon.endtime,
                valueDesc: parseFloat(item.coupon.rate) * 100,
                unitDesc: '折',
                rate: item.coupon.rate
            })
        })
    }

}

const onPayConfirm = ({ selectedValues, selectedOptions }) => {
    payName.value = selectedOptions[0]?.text;
    pay.value = selectedOptions[0]?.value;
    showPayPicker.value = false;
};

const onCouponChange = (index) => {
    showList.value = false;
    chosenCoupon.value = index;
};


const total = computed(() => {
    let num = 0;
    num = productlist.value.reduce((index, item) => index + parseFloat(item.total), 0,)
    // 使用优惠券
    if (chosenCoupon.value != -1) {
        let coupon = couponlist.value[chosenCoupon.value]
        let rate = parseFloat(coupon.rate)
        let totals = productlist.value.reduce((index, item) => index + parseFloat(item.total), 0,)
        // 打折之后的价格
        num = (rate * totals).toString()
        let key = num.indexOf('.')
        num = num.substring(0, key + 3)
        // 优惠券金额
        let price = (totals - num) * 100
        couponlist.value[chosenCoupon.value].value = price
    }

    return num * 100;
})

const onSubmit = async () => {

    if (!payName.value) {
        error('请选择支付方式');
        return false;
    }

    if (JSON.stringify(Address.value) == '{}') {
        error('请选择收货地址');
        return false;
    }

    let data = {
        busid: LoginUser.id,
        businessaddrid: Address.value.id,
        amount: total.value / 100,
        remark: remark.value,
        couponid: couponlist.value[chosenCoupon.value] ? couponlist.value[chosenCoupon.value].id : 0,
        pay: pay.value,
        cartids: cartids,
        isDirectlyBuy: isDirectlyBuy
    }

    let result = await Api.OrderAdd(data);
    if (result.code == 1) {
        success({
            message: result.msg,
            onClose: () => {
                proxy.$router.push('/order/index')
            }
        });

    } else {
        error(result.msg);
    }
}

</script>
<style scoped>
/* 组件穿透样式写法 */
:deep(.van-field__control:read-only) {
    text-align: right;
}
</style>